'''
Author: Yizhe Li 1362800827@qq.com
Date: 2024-06-23 07:09:13
LastEditors: Yizhe Li 1362800827@qq.com
LastEditTime: 2024-06-26 16:09:25
FilePath: /ubuntu/HuibanApi-Py/kimi_internet_search.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from openai import OpenAI
import requests
from bs4 import BeautifulSoup
from urllib.parse import quote
 
client = OpenAI(
    api_key = "sk-LH3VLFgensr0E7cRyc00XB9STDPbAOjqgLZfZldDuvlJ2sUe",
    base_url = "https://api.moonshot.cn/v1",
)

#region Flask temp code
from flask import Flask, request, jsonify
import json
app = Flask(__name__)

history = [
    {"role": "system", "content": "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。"}
]

# 历史记录保存不超过 5 轮对话
chatNumber = 0
maxChatNumber = 5

# 定义外部工具，使用 bing 搜索
def search_with_bing(query):
    query = quote(query)
    url = f'https://cn.bing.com/search?q={query}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
    }
    resp = requests.get(url, headers=headers)
    soup = BeautifulSoup(resp.text, 'html.parser')
    
    result_elements = soup.select('#b_results > li')
    data = []

    # 返回前 3 条结果
    for parent in result_elements[:1]:
        if parent.select_one('h2') is None:
            continue
        data.append({
            'title': parent.select_one('h2').text,
            'abstract': parent.select_one('div.b_caption > p').text.replace('\u2002', ' '),
            'link': parent.select_one('div.b_tpcn > a').get('href')
        })
    print(f"data: {data}")
    print(f"soup: {soup.select_one('#b_results').text[:100]}")
    # 如果 data 为 [] 则返回适当长度的 soup 有效内容（不宜过长），否则正常返回 data
    return data if data != [] else soup.select_one('#b_results').text[:100]
 
def chat(query, history):
    search_result = search_with_bing(query)
    history.append({
        "role": "user", 
        # "content": f"请基于<<<context>>>{search_with_bing(query)}<<<context>>>，回答：{query}"
        "content": f"请基于搜索结果：\"\"\"{search_result}\"\"\"，回答：{query}"
        # "content": f"{query}"
    })
    completion = client.chat.completions.create(
        model="moonshot-v1-8k",
        messages=history,
        temperature=0.3,
    )
    print(completion.choices[0].message)
    result = completion.choices[0].message.content
    history.append({
        "role": "assistant",
        "content": result
    })
    return result

@app.route('/chat', methods=['POST'])
def myChat():
    global chatNumber, maxChatNumber, history
    chatNumber += 1
    if chatNumber > maxChatNumber:
        history.pop(0)
        chatNumber = maxChatNumber
    data = request.json
    message = data.get('userMsg', "")
    return chat(message, history)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
#endregion